<%--
  Created by IntelliJ IDEA.
  User: CBo
  Date: 2025/9/24
  Time: 20:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="header.jsp"/>
<html>
<head>
    <title>Title</title>
    <style>
        .container {
            max-width: 1200px;
        }

        .search-card {
            margin-bottom: 20px;
        }

        .search-form {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .search-field {
            flex: 1;
            min-width: 250px;
        }

        .action-buttons .btn {
            margin-right: 5px;
        }

        .table-responsive {
            min-height: 400px;
        }

        .card {
            --bs-card-border-width: 0;
        }

        .card-body {
            padding: 0;
        }

        .search-actions {
            display: flex;
            gap: 10px;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <!-- 搜索区域 -->
    <div class="card search-card">
        <div class="card-body">
            <div class="search-form">
                <div class="search-field">
                    <label for="searchType" class="form-label">查询条件</label>
                    <select class="form-select" id="searchType">
                        <option value="all">全部班级</option>
                        <option value="classId">按班级编号查询</option>
                        <option value="className">按班级名称查询</option>
                        <option value="subjectId">按专业编号查询</option>
                        <option value="courseId">按课程编号查询</option>
                        <option value="teacherId">按教师编号查询</option>
                        <option value="roomId">按教室编号查询</option>
                    </select>
                </div>

                <div class="search-field" id="classIdField">
                    <label for="classId" class="form-label">班级编号</label>
                    <input type="text" class="form-control" id="classId" placeholder="输入班级编号">
                </div>

                <div class="search-field" id="classNameField">
                    <label for="className" class="form-label">班级名称</label>
                    <input type="text" class="form-control" id="className" placeholder="输入班级名称">
                </div>

                <div class="search-field" id="subjectIdField">
                    <label for="subjectId" class="form-label">专业编号</label>
                    <select class="form-select" id="subjectId">
                        <option value="">请选择专业</option>
                    </select>
                </div>

                <div class="search-field" id="courseIdField">
                    <label for="courseId" class="form-label">课程编号</label>
                    <select class="form-select" id="courseId">
                        <option value="">请选择课程</option>
                    </select>
                </div>

                <div class="search-field" id="teacherIdField">
                    <label for="teacherId" class="form-label">教师编号</label>
                    <select class="form-select" id="teacherId">
                        <option value="">请选择教师</option>
                    </select>
                </div>

                <div class="search-field" id="roomIdField">
                    <label for="roomId" class="form-label">教室编号</label>
                    <select class="form-select" id="roomId">
                        <option value="">请选择教室</option>
                    </select>
                </div>

                <div class="search-actions">
                    <a id="selectClasses">
                        <button type="button" class="btn btn-primary" id="searchBtn">
                            <i class="bi bi-search"></i> 查询
                        </button>
                    </a>
                    <a id="resetSelect">
                        <button type="button" class="btn btn-outline-secondary" id="resetBtn">
                            <i class="bi bi-arrow-clockwise"></i> 重置
                        </button>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加按钮 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5>班级列表</h5>
        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addClassesModal">
            <i class="bi bi-plus-circle"></i> 添加班级
        </button>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>班级编号</th>
                        <th>班级名称</th>
                        <th>专业</th>
                        <th>当前课程</th>
                        <th>带班教师</th>
                        <th>教室</th>
                        <th>学生列表</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="classesTableBody">
                    <c:set var="pageitem" scope="session" value="${page.items}"/>
                    <c:if test="${empty pageitem}">
                        <tr>
                            <td colspan="9" class="text-center">没有找到匹配的班级数据</td>
                        </tr>
                    </c:if>
                    <c:forEach items="${sessionScope.page.items}" var="classes" varStatus="status">
                        <tr>
                            <td>${(sessionScope.page.pageIndex-1)*sessionScope.page.pageSize+status.count}</td>
                            <td>${classes.id}</td>
                            <td>${classes.name}</td>
                            <td>${classes.subjectName}</td>
                            <td>${classes.courseName}</td>
                            <td>${classes.teacherName}</td>
                            <td>${classes.roomName}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary student-list-btn" data-id="${classes.id}">
                                    <i class="bi bi-card-list"></i> 详情
                                </button>
                            </td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-outline-primary edit-btn" data-id="${classes.id}"
                                        id="editBtn">
                                    <i class="bi bi-pencil"></i> 修改
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${classes.id}"
                                        data-name="${classes.name}">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
            <!-- 分页 -->
            <jsp:include page="pagination.jsp"/>
        </div>
    </div>

</div>

<!-- 添加班级模态框 -->
<div class="modal fade" id="addClassesModal" tabindex="-1" aria-labelledby="addClassesModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addClassesModalLabel">添加班级</h5>
                <button type="button" id="btn-addClasses-close" class="btn-close" data-bs-dismiss="modal"
                        aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addClassesForm">
                    <div class="mb-3">
                        <label for="newClassesName" class="form-label">班级名称</label>
                        <input type="text" class="form-control" id="newClassesName" required>
                    </div>
                    <div class="mb-3">
                        <label for="newSubjectId" class="form-label">专业</label>
                        <select class="form-select" id="newSubjectId" required>
                            <option value="">请选择专业</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="newCourseId" class="form-label">当前课程</label>
                        <select class="form-select" id="newCourseId" required>
                            <option value="">请选择课程</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="newTeacherId" class="form-label">带班教师</label>
                        <select class="form-select" id="newTeacherId" required>
                            <option value="">请选择教师</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="newRoomId" class="form-label">教室</label>
                        <select class="form-select" id="newRoomId" required>
                            <option value="">请选择教室</option>
                        </select>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <label for="newClassesState" class="form-label">班级状态</label>
                        <input type="checkbox" class="form-check-input" id="newClassesState">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancelAddClassesBtn" data-bs-dismiss="modal">取消
                </button>
                <button type="button" class="btn btn-primary" id="saveAddClassesBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑班级模态框 -->
<div class="modal fade" id="editClassesModal" tabindex="-1" aria-labelledby="editClassesModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editClassesModalLabel">编辑班级</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editClassesForm">
                    <input type="hidden" id="editClassesId">
                    <div class="mb-3">
                        <label for="editClassesName" class="form-label">班级名称</label>
                        <input type="text" class="form-control" id="editClassesName" required>
                    </div>
                    <div class="mb-3">
                        <label for="editClassesSubject" class="form-label">专业</label>
                        <select class="form-select" id="editClassesSubject" required>
                            <option value="">请选择专业</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editClassesCurrentCourse" class="form-label">当前课程</label>
                        <select class="form-select" id="editClassesCurrentCourse" required>
                            <option value="">请选择课程</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editClassesCurrentTeacher" class="form-label">带班教师</label>
                        <select class="form-select" id="editClassesCurrentTeacher" required>
                            <option value="">请选择带班教师</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="editClassesRoom" class="form-label">教室</label>
                        <select class="form-select" id="editClassesRoom" required>
                            <option value="">请选择教室</option>
                        </select>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <label for="editClassesState" class="form-label">班级状态</label>
                        <input type="checkbox" class="form-check-input" id="editClassesState">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditClassesBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除班级：<span id="deleteClassesName" class="fw-bold"></span> 吗？此操作不可逆。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const classIdField = document.getElementById('classIdField');//班级编号
    const classNameField = document.getElementById('classNameField');//班级名称
    const subjectIdField = document.getElementById('subjectIdField');//专业编号
    const courseIdField = document.getElementById('courseIdField');//课程编号
    const teacherIdField = document.getElementById('teacherIdField');//教师编号
    const roomIdField = document.getElementById('roomIdField');//教室编号
    let selectClasses = document.getElementById('selectClasses');//查询班级
    let resetSelect = document.getElementById('resetSelect')//重置
    let subjects = [];
    let courses = [];
    let teachers = [];
    let classRooms = [];
    let currentClassId = null;
    let classes = [];

    function initPage() {
        // 默认隐藏查询字段
        toggleSearchFields();

        // 监听查询条件变化
        document.getElementById('searchType').addEventListener('change', toggleSearchFields);
        // document.getElementById('editBtn').addEventListener('click', handleEdit);
        getAllSubject();
        getAllCourse();
        getAllTeacher();
        getAllClassRoom();
        getAllSubjectInfo();
    }

    // 根据选择的查询类型显示/隐藏字段
    function toggleSearchFields() {
        let searchType = document.getElementById('searchType').value;
        // 重置字段
        classIdField.style.display = 'none';
        classNameField.style.display = 'none';
        subjectIdField.style.display = 'none';
        courseIdField.style.display = 'none';
        teacherIdField.style.display = 'none';
        roomIdField.style.display = 'none';

        // 根据选择显示相应字段
        if (searchType === 'classId') {
            classIdField.style.display = 'block';
        }
        if (searchType === 'className') {
            classNameField.style.display = 'block';
        }
        if (searchType === 'subjectId') {
            subjectIdField.style.display = 'block';
        }
        if (searchType === 'courseId') {
            courseIdField.style.display = 'block';
        }
        if (searchType === 'teacherId') {
            teacherIdField.style.display = 'block';
        }
        if (searchType === 'roomId') {
            roomIdField.style.display = 'block';
        }

    }

    //专业列表
    function getAllSubject() {
        let selectSubject = document.getElementById('subjectId');
        $.ajax({
            url: "./allSubjectInfo",
            type: "GET",
            dataType: "json",
            success: function (data) {
                subjects = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < subjects.length; i++) {
                    let option = document.createElement('option');
                    option.value = subjects[i].id;
                    option.text = subjects[i].name;
                    fragment.appendChild(option);
                }
                selectSubject.appendChild(fragment);
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 课程列表
    function getAllCourse() {
        let selectCourse = document.getElementById('courseId');
        $.ajax({
            url: "./allCourseInfo",
            type: "GET",
            dataType: "json",
            success: function (data) {
                courses = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < courses.length; i++) {
                    let option = document.createElement('option');
                    option.value = courses[i].id;
                    option.text = courses[i].name;
                    fragment.appendChild(option);
                }
                selectCourse.appendChild(fragment);
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 教师列表
    function getAllTeacher() {
        let selectTeacher = document.getElementById('teacherId');
        $.ajax({
            url: "./allTeacherInfo",
            type: "GET",
            dataType: "json",
            success: function (data) {
                teachers = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < teachers.length; i++) {
                    let option = document.createElement('option');
                    option.value = teachers[i].id;
                    option.text = teachers[i].name;
                    fragment.appendChild(option);
                }
                selectTeacher.appendChild(fragment);
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 教室列表
    function getAllClassRoom() {
        let selectClassRoom = document.getElementById('roomId');
        $.ajax({
            url: "./allClassRoomInfo",
            type: "GET",
            dataType: "json",
            success: function (data) {
                classRooms = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < classRooms.length; i++) {
                    let option = document.createElement('option');
                    option.value = classRooms[i].id;
                    option.text = classRooms[i].name;
                    fragment.appendChild(option);
                }
                selectClassRoom.appendChild(fragment);
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    //模态框专业列表
    function getAllSubjectInfo(modalType) {
        let selectNewSubject = modalType === 'edit' ? document.getElementById('editClassesSubject') : document.getElementById('newSubjectId');
        selectNewSubject.innerHTML = '<option value="">请选择专业</option>';
        $.ajax({
            url: "./allSubjectInfo",
            type: "GET",
            dataType: "json",
            success: function (data) {
                subjects = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < subjects.length; i++) {
                    let option = document.createElement('option');
                    option.value = subjects[i].id;
                    option.text = subjects[i].name;
                    fragment.appendChild(option);
                }
                selectNewSubject.appendChild(fragment);

                // 如果是编辑模式，需要重新设置选中值
                if (modalType === 'edit' && currentClassId) {
                    let classItem = classes.find(c => c.id === parseInt(currentClassId));
                    if (classItem) {
                        setTimeout(() => {
                            selectNewSubject.value = classItem.subjectId;
                        }, 0);
                    }
                }
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 模态框课程列表
    function getAllCourseInfo(modalType) {
        let selectNewCourse = modalType === 'edit' ? document.getElementById('editClassesCurrentCourse') : document.getElementById('newCourseId');
        selectNewCourse.innerHTML = '<option value="">请选择课程</option>';
        let selectedSubjectId = modalType === 'edit' ? document.getElementById('editClassesSubject').value : document.getElementById('newSubjectId').value;
        if (selectedSubjectId === '') {
            return;
        }
        $.ajax({
            url: "./getCourseBySubjectId?subjectId=" + selectedSubjectId,
            type: "GET",
            dataType: "json",
            success: function (data) {
                courses = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < courses.length; i++) {
                    let option = document.createElement('option');
                    option.value = courses[i].id;
                    option.text = courses[i].name;
                    fragment.appendChild(option);
                }
                selectNewCourse.appendChild(fragment);

                // 如果是编辑模式，需要重新设置选中值
                if (modalType === 'edit' && currentClassId) {
                    let classItem = classes.find(c => c.id === parseInt(currentClassId));
                    if (classItem) {
                        setTimeout(() => {
                            document.getElementById('editClassesCurrentCourse').value = classItem.courseId;
                            // 触发课程选择事件，加载教师列表
                            document.getElementById('editClassesCurrentCourse').dispatchEvent(new Event('change'));
                        }, 0);
                    }
                }
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 模态框教师列表
    function getAllTeacherInfo(modalType) {
        let selectNewTeacher = modalType === 'edit' ? document.getElementById('editClassesCurrentTeacher') : document.getElementById('newTeacherId');
        selectNewTeacher.innerHTML = '<option value="">请选择带班教师</option>';
        let selectedCourseId = modalType === 'edit' ? document.getElementById('editClassesCurrentCourse').value : document.getElementById('newCourseId').value;
        if (selectedCourseId === '') {
            return;
        }
        $.ajax({
            url: "./getTeacherByCourseId?courseId=" + selectedCourseId,
            type: "GET",
            dataType: "json",
            success: function (data) {
                teachers = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < teachers.length; i++) {
                    let option = document.createElement('option');
                    option.value = teachers[i].id;
                    option.text = teachers[i].name;
                    fragment.appendChild(option);
                }
                selectNewTeacher.appendChild(fragment);

                // 如果是编辑模式，需要重新设置选中值
                if (modalType === 'edit' && currentClassId) {
                    let classItem = classes.find(c => c.id === parseInt(currentClassId));
                    if (classItem) {
                        setTimeout(() => {
                            document.getElementById('editClassesCurrentTeacher').value = classItem.teacherId;
                        }, 0);
                    }
                }
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 模态框教室列表
    function getAllClassRoomInfo(modalType) {
        let selectNewClassRoom = modalType === 'edit' ? document.getElementById('editClassesRoom') : document.getElementById('newRoomId');
        selectNewClassRoom.innerHTML = '<option value="">请选择教室</option>';
        let selectedSubjectId = modalType === 'edit' ? document.getElementById('editClassesSubject').value : document.getElementById('newSubjectId').value;
        if (selectedSubjectId === '') {
            return;
        }
        $.ajax({
            url: "./getClassRoomBySubjectId?subjectId=" + selectedSubjectId,
            type: "GET",
            dataType: "json",
            success: function (data) {
                classRooms = data;
                let fragment = document.createDocumentFragment();
                for (let i = 0; i < classRooms.length; i++) {
                    let option = document.createElement('option');
                    option.value = classRooms[i].id;
                    option.text = classRooms[i].name;
                    fragment.appendChild(option);
                }
                selectNewClassRoom.appendChild(fragment);

                // 如果是编辑模式，需要重新设置选中值
                if (modalType === 'edit' && currentClassId) {
                    let classItem = classes.find(c => c.id === parseInt(currentClassId));
                    if (classItem) {
                        setTimeout(() => {
                            document.getElementById('editClassesRoom').value = classItem.roomId;
                        }, 0);
                    }
                }
            }
            , error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    // 处理查询
    function handleSearch() {
        let searchType = document.getElementById('searchType').value;
        let classId = document.getElementById('classId').value.trim();
        let className = document.getElementById('className').value.trim();
        let subjectId = document.getElementById('subjectId').value.trim();
        let courseId = document.getElementById('courseId').value.trim();
        let teacherId = document.getElementById('teacherId').value.trim();
        let roomId = document.getElementById('roomId').value.trim();
        if (searchType === 'classId' && classId !== null && classId !== "") {
            selectClasses.href = "./select?classId=" + classId + "";
        } else if (searchType === 'className' && className !== null && className !== "") {
            selectClasses.href = "./select?className=" + className + "";
        } else if (searchType === 'subjectId' && subjectId !== null && subjectId !== "") {
            selectClasses.href = "./select?subjectId=" + subjectId + "";
        } else if (searchType === 'courseId' && courseId !== null && courseId !== "") {
            selectClasses.href = "./select?courseId=" + courseId + "";
        } else if (searchType === 'teacherId' && teacherId !== null && teacherId !== "") {
            selectClasses.href = "./select?teacherId=" + teacherId + "";
        } else if (searchType === 'roomId' && roomId !== null && roomId !== "") {
            selectClasses.href = "./select?roomId=" + roomId + "";
        } else {
            selectClasses.href = "./classesinfo"
        }
    }

    // 重置查询
    function handleReset() {
        document.getElementById('searchType').value = 'all';
        document.getElementById('classId').value = '';
        document.getElementById('className').value = '';
        document.getElementById('subjectId').value = '';
        document.getElementById('courseId').value = '';
        document.getElementById('teacherId').value = '';
        document.getElementById('roomId').value = '';
        toggleSearchFields();
        resetSelect.href = "./classesinfo"
    }

    //保存添加
    async function saveAdd() {
        let newClassName = document.getElementById('newClassesName').value.trim();
        let newSubjectId = document.getElementById('newSubjectId').value;
        let newCourseId = document.getElementById('newCourseId').value;
        let newTeacherId = document.getElementById('newTeacherId').value;
        let newRoomId = document.getElementById('newRoomId').value;
        let newClassesState = document.getElementById('newClassesState').checked;
        if (newClassName === '' || newSubjectId === '' || newCourseId === '' || newTeacherId === '' || newRoomId === '') {
            alert('请填写完整信息');
            return;
        }

        // 获取所有班级信息用于检查教室占用
        classes = await getAllClassInfoForEdit();

        // 检查教室是否已被其他班级使用
        let isRoomOccupied = false;
        for (let i = 0; i < classes.length; i++) {
            if (classes[i].roomId == newRoomId) {
                isRoomOccupied = true;
                break;
            }
        }

        if (isRoomOccupied) {
            alert('该教室已被其他班级占用，请选择其他教室！');
            return;
        }
        $.ajax({
            url: './add',
            type: 'POST',
            data: {
                className: newClassName,
                subjectId: newSubjectId,
                courseId: newCourseId,
                teacherId: newTeacherId,
                roomId: newRoomId,
                state: newClassesState
            },
            dataType: 'json',
            success: function (data) {
                alert('添加成功');
                window.location.href = "./classesinfo";
            },
            error: function (xhr, status, error) {
                alert('添加失败');
            }
        })

    }

    //处理修改
    async function handleEdit(event) {
        let modalType = 'edit';
        currentClassId = event.currentTarget.getAttribute('data-id');
        classes = await getAllClassInfoForEdit();
        let classItem = classes.find(c => c.id === parseInt(currentClassId));

        if (classItem) {
            // 填充基本信息
            document.getElementById('editClassesName').value = classItem.name;

            // 加载专业列表并设置选中值
            getAllSubjectInfo(modalType);

            // 等待DOM更新后设置专业选中值并触发change事件
            setTimeout(() => {
                const subjectSelect = document.getElementById('editClassesSubject');
                subjectSelect.value = classItem.subjectId;

                // 触发专业选择事件，加载课程列表
                subjectSelect.dispatchEvent(new Event('change'));

                // 等待课程列表加载完成后再设置值
                setTimeout(() => {
                    const courseSelect = document.getElementById('editClassesCurrentCourse');
                    courseSelect.value = classItem.courseId;

                    // 触发课程选择事件，加载教师列表
                    courseSelect.dispatchEvent(new Event('change'));

                    // 等待教师列表加载完成后再设置值
                    setTimeout(() => {
                        document.getElementById('editClassesCurrentTeacher').value = classItem.teacherId;
                    }, 100);
                }, 100);

                // 加载教室列表
                getAllClassRoomInfo(modalType);

                // 等待教室列表加载完成后再设置值
                setTimeout(() => {
                    document.getElementById('editClassesRoom').value = classItem.roomId;
                }, 100);
            }, 100);

            // 设置状态
            document.getElementById('editClassesState').checked = classItem.state;

            // 显示模态框
            const editModal = new bootstrap.Modal(document.getElementById('editClassesModal'));
            editModal.show();
        }
    }

    //保存修改
    async function saveEdit() {
        let classId = currentClassId;
        let className = document.getElementById('editClassesName').value;
        let subjectId = document.getElementById('editClassesSubject').value;
        let courseId = document.getElementById('editClassesCurrentCourse').value;
        let teacherId = document.getElementById('editClassesCurrentTeacher').value;
        let roomId = document.getElementById('editClassesRoom').value;
        let classState = document.getElementById('editClassesState').checked;

        // 获取所有班级信息用于检查教室占用
        classes = await getAllClassInfoForEdit();

        // 检查教室是否已被其他班级使用
        let isRoomOccupied = false;
        for (let i = 0; i < classes.length; i++) {
            // 检查除了当前班级外，是否有其他班级使用了该教室
            if (classes[i].id != classId && classes[i].roomId == roomId) {
                isRoomOccupied = true;
                break;
            }
        }

        if (isRoomOccupied) {
            alert('该教室已被其他班级占用，请选择其他教室！');
            return;
        }

        $.ajax({
            type: "POST",
            url: "./update",
            data: {
                id: classId,
                name: className,
                subjectId: subjectId,
                courseId: courseId,
                teacherId: teacherId,
                roomId: roomId,
                state: classState,
            },
            dataType: "json",
            success: function (data) {
                const editModal = bootstrap.Modal.getInstance(document.getElementById('editClassesModal'));
                editModal.hide();
                alert('修改成功')
                // 重定向到查询页面
                window.location.href = "./classesinfo";
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        })
    }

    //查询所有班级
    const getAllClassInfoForEdit = function () {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: "GET",
                url: "./allClassesInfo",
                dataType: "json",
                success: resolve,
                error: reject
            })
        })
    }

    //处理删除
    function handleDelete(event) {
        let classesId = event.currentTarget.getAttribute('data-id');
        let classesName = event.currentTarget.getAttribute('data-name');
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        document.getElementById('deleteClassesName').innerText = classesName;
        deleteModal.show();
        document.getElementById('confirmDeleteBtn').addEventListener('click', function () {
            $.ajax({
                type: "GET",
                url: "./delete",
                data: {
                    id: classesId
                },
                dataType: "json",
                success: function (data) {
                    console.log(data)
                    const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal'));
                    deleteModal.hide();
                    alert('删除成功');
                    window.location.href = "./classesinfo";
                },
                error: function (xhr, status, error) {
                    alert('删除失败');
                    console.log(error);
                }
            })

        })
    }

    //添加班级 取消时清空表单
    function handleCancel() {
        document.getElementById('newClassesName').value = '';
        document.getElementById('newSubjectId').value = '';
        document.getElementById('newCourseId').value = '';
        document.getElementById('newTeacherId').value = '';
        document.getElementById('newRoomId').value = '';
        document.getElementById('newClassesState').checked = false;
    }

    //班级 学生列表详情
    function handleStudentList(event) {
        let classId = event.currentTarget.getAttribute('data-id');
        window.location.href = "./classstudentlist?classId=" + classId;
    }


    //初始化事件监听
    document.getElementById('searchBtn').addEventListener('click', handleSearch);
    document.getElementById('resetBtn').addEventListener('click', handleReset);
    document.getElementById('newSubjectId').addEventListener('change', getAllCourseInfo);
    document.getElementById('newCourseId').addEventListener('change', getAllTeacherInfo);
    document.getElementById('newSubjectId').addEventListener('change', getAllClassRoomInfo);
    document.getElementById('editClassesSubject').addEventListener('change', function () {
        getAllCourseInfo('edit');
    });
    document.getElementById('editClassesCurrentCourse').addEventListener('change', function () {
        getAllTeacherInfo('edit');
    });
    document.querySelectorAll('.edit-btn').forEach(editBtn => {
        editBtn.addEventListener('click', handleEdit);
    })
    document.getElementById('saveEditClassesBtn').addEventListener('click', function () {
        saveEdit();
    });
    document.getElementById('saveAddClassesBtn').addEventListener('click', function () {
        saveAdd();
    });
    document.querySelectorAll('.delete-btn').forEach(deleteBtn => {
        deleteBtn.addEventListener('click', handleDelete);
    })
    document.getElementById('cancelAddClassesBtn').addEventListener('click', handleCancel);
    document.getElementById('btn-addClasses-close').addEventListener('click', handleCancel);
    document.querySelectorAll('.student-list-btn').forEach(studentListBtn => {
        studentListBtn.addEventListener('click', handleStudentList);
    })

    //初始化页面
    initPage();
</script>
</body>
</html>
<jsp:include page="footer.jsp"/>
